/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import entity.Barang;
import entity.User;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jpa.BarangJpaController;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author has
 */
@WebServlet(name = "/uploadFoto", urlPatterns = {"/uploadFoto"})
public class uploadFoto extends HttpServlet {

    private static final String TMP_DIR_PATH = "c:/tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "photos";
    private File destinationDir;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        RequestDispatcher dis = null;
        String page = request.getParameter("page");
        if (page.equals("upload")) {
            dis = request.getRequestDispatcher("inputFotoBarang.jsp");
            dis.forward(request, response);
        } else {
            HttpSession session = request.getSession();
            Barang barang = new Barang();
            BarangJpaController bjc = new BarangJpaController();
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            fileItemFactory.setRepository(tmpDir);
            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
            try {
                List items = uploadHandler.parseRequest(request);
                Iterator itr = items.iterator();
                /* melakukan eksekusi proses upload
                 */ while (itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    File file = new File(destinationDir, item.getName());
                    item.write(file);
                    String fotoBarang = DESTINATION_DIR_PATH + "/" + file.getName();
                    /* menenetukan nama tempat penyimpanan file upload pada database
                     */
                    if (session.getAttribute("username") != null) {
                        barang = null;
                        barang = (Barang) session.getAttribute("barang");
                        barang.setFotoBarang(fotoBarang);
                        session.setAttribute("barang", barang);
                        bjc.edit(barang);
                        dis = request.getRequestDispatcher("detilBarang.jsp");
                        dis.forward(request, response);
                    } else {
                        session.setAttribute("error", "sudah logout sebelumnya");
                        dis = request.getRequestDispatcher("index.jsp");
                        dis.forward(request, response);
                    }
                }

            } catch (FileUploadException ex) {
                log("Error encountered while parsing the request", ex);
            } catch (Exception ex) {
                log("Error encountered while uploading file", ex);
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
